package com.rykj.energy.database.server;

import com.rykj.energy.database.pojo.BasicNotice;
import com.rykj.energy.database.service.INoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class NoticeInfoCacheServer {
    
    @Autowired
    private INoticeService noticeService;
    private static Map<String, BasicNotice> cache;
    
    @PostConstruct
    public void init(){
        refresh();
    }
    
    @Scheduled(fixedRate=60*1000L)
    public void refresh(){
        List<BasicNotice> notices = noticeService.getList();
        Map<String, BasicNotice> news = new HashMap<String, BasicNotice>();
        cache = news;
        for(BasicNotice notice : notices) {
            cache.put(notice.getBusinessType(), notice);
        }
    }
    
    private static Map<String, BasicNotice> getInstance() {
        while(cache == null) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return cache;
    }
    public static String getBusinessName(String type) {
        BasicNotice notice = getInstance().get(type);
        return notice != null?notice.getBusineesName():"N/A";
    }
    
    public static BasicNotice getNotice(String type) {
        BasicNotice notice = getInstance().get(type);
        return notice;
    }
    

}
